<?php

class TwitterService extends Auth
{
    public $clientId='';
    public $clientSecret='';
    protected $token='';
    protected $userInfo=false, $serviceName='twitter';

    const URL_REQUEST_TOKEN='https://api.twitter.com/oauth/request_token';
    const URL_AUTHORIZE='https://api.twitter.com/oauth/authenticate';
    const URL_ACCESS_TOKEN='https://api.twitter.com/oauth/access_token';
    const URL_ACCOUNT_DATA='https://api.twitter.com/1.1/users/show.json';

    public function getUserInfo()
    {
        $info=$this->userInfo;
        $firstName='';
        $secondName='';
        if(isset($info->name)){
            $name=explode(' ',$info->name);
            if(isset($name[0]) && isset($name[1])){
                $firstName=$name[0];
                $secondName=$name[1];
            }else{
                $firstName=$this->userInfo;
            }
        }

        return array(
            'user'=>array(
                'login'=>isset($info->screen_name) ? $info->screen_name : (isset($info->id) ? $info->id : ''),
                'userName'=>isset($info->screen_name) ? $info->screen_name : (isset($info->id) ? $info->id : ''),
                'password'=>'',
                'confirmCode'=>'',
                'email'=>isset($info->email) ? $info->email : '',
                'isConfirmed'=>1,
                'isActive'=>1,
            ),
            'profile'=>array(
                'firstName'=>$firstName,
                'lastName'=>$secondName,
                'sex'=>0,
                'img'=>isset($info->profile_image_url) ? $info->profile_image_url : '',
            ),
        );
    }

    public function getToken()
    {
        return $this->token;
    }

    public function getServiceName()
    {
        return $this->serviceName;
    }

    public function firstRequest()
    {
        $returnUrl=$this->getReturnUrl();
        $time=time();
        $nonce=md5(uniqid(rand(),true));

        $oauthBaseText='GET&'.urlencode(self::URL_REQUEST_TOKEN).'&'.
            urlencode('oauth_callback='.urlencode($returnUrl).'&').
            urlencode('oauth_consumer_key='.$this->clientId.'&').
            urlencode('oauth_nonce='.$nonce.'&').
            urlencode('oauth_signature_method=HMAC-SHA1&').
            urlencode('oauth_timestamp='.$time.'&').
            urlencode('oauth_version=1.0');

        $signature=base64_encode(hash_hmac('sha1',$oauthBaseText,$this->clientSecret.'&',true));

        $redirectUrl=self::URL_REQUEST_TOKEN.
            '?oauth_callback='.urlencode($returnUrl).
            '&oauth_consumer_key='.$this->clientId.
            '&oauth_nonce='.$nonce.
            '&oauth_signature='.urlencode($signature).
            '&oauth_signature_method=HMAC-SHA1'.
            '&oauth_timestamp='.$time.
            '&oauth_version=1.0';

        try{
            $result=file_get_contents($redirectUrl);
            parse_str($result,$arrayResult);

            Yii::app()->session['token']=$token=$arrayResult['oauth_token'];
            Yii::app()->session['tokenSecret']=$arrayResult['oauth_token_secret'];
            $requestUrl=self::URL_AUTHORIZE.'?oauth_token='.$token;

            Yii::app()->request->redirect($requestUrl);
        }catch(Exception $e){
            $this->quit($e);
        }

        return false;
    }

    public function secondRequest()
    {
        if(isset($_GET['oauth_token']) && isset($_GET['oauth_verifier']) && $tokenSecret=Yii::app()->session['tokenSecret']){
            $token=$_GET['oauth_token'];
            $verifier=$_GET['oauth_verifier'];
            $time=time();
            $nonce=md5(uniqid(rand(),true));

            $oauthBaseText='GET&'.
                urlencode(self::URL_ACCESS_TOKEN).'&'.
                urlencode('oauth_consumer_key='.$this->clientId.'&').
                urlencode('oauth_nonce='.$nonce.'&').
                urlencode('oauth_signature_method=HMAC-SHA1&').
                urlencode('oauth_token='.$token.'&').
                urlencode('oauth_timestamp='.$time.'&').
                urlencode('oauth_verifier='.$verifier.'&').
                urlencode('oauth_version=1.0');

            $signature=base64_encode(hash_hmac('sha1',$oauthBaseText,$this->clientSecret.'&'.$tokenSecret,true));

            $redirectUrl=self::URL_ACCESS_TOKEN.
                '?oauth_nonce='.$nonce.
                '&oauth_signature_method=HMAC-SHA1'.
                '&oauth_timestamp='.$time.
                '&oauth_consumer_key='.$this->clientId.
                '&oauth_token='.urlencode($token).
                '&oauth_verifier='.urlencode($verifier).
                '&oauth_signature='.urlencode($signature).
                '&oauth_version=1.0';

            unset(Yii::app()->session['token'],Yii::app()->session['tokenSecret']);
            return $this->thirdRequest($redirectUrl);
        }

        return false;
    }

    private function thirdRequest($requestUrl)
    {
        try{
            $result=file_get_contents($requestUrl);
            parse_str($result,$arrayResult);

            if(!isset($arrayResult['oauth_token']) || !isset($arrayResult['oauth_token_secret']) || !isset($arrayResult['screen_name'])) return false;

            $token=$arrayResult['oauth_token'];
            $tokenSecret=$arrayResult['oauth_token_secret'];
            $name=$arrayResult['screen_name'];

            $time=time();
            $nonce=md5(uniqid(rand(),true));

            $oauthBaseText='GET&'.
                urlencode(self::URL_ACCOUNT_DATA).'&'.
                urlencode('oauth_consumer_key='.$this->clientId.'&').
                urlencode('oauth_nonce='.$nonce.'&').
                urlencode('oauth_signature_method=HMAC-SHA1&').
                urlencode('oauth_timestamp='.$time.'&').
                urlencode('oauth_token='.$token.'&').
                urlencode('oauth_version=1.0&').
                urlencode('screen_name='.$name);

            $signature=base64_encode(hash_hmac('sha1',$oauthBaseText,$this->clientSecret.'&'.$tokenSecret,true));

            $redirectUrl=self::URL_ACCOUNT_DATA.
                '?oauth_consumer_key='.$this->clientId.
                '&oauth_nonce='.$nonce.
                '&oauth_signature='.urlencode($signature).
                '&oauth_signature_method=HMAC-SHA1'.
                '&oauth_timestamp='.$time.
                '&oauth_token='.urlencode($token).
                '&oauth_version=1.0'.
                '&screen_name='.$name;

            if(is_object($result=json_decode(file_get_contents($redirectUrl)))){
                if(isset($result->error_msg)) $this->quit($result->error_msg);
                $this->userInfo=$result;
                return true;
            }
        }catch(Exception $e){
            $this->quit($e);
        }

        return false;
    }
}